package com.wlstock.funi.utils;

import com.wlstock.funi.fundenum.KLINE_PERIOD;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StockUtils {
	
	
	public static final int ALLSTOCK_NUMS = 2809;
	public static final String KEY_TITLE = "title";
	public static final String KEY_RESULT = "result";
	public static final String KEY_COUNT = "count";

	public static int caculatePeriodNumsPerDay(KLINE_PERIOD period){
		int PERIOD_TRADE_HOURES = 4;
		switch (period){
			case MIN5:
				return PERIOD_TRADE_HOURES * 12;
			case MIN10:
				return PERIOD_TRADE_HOURES * 6;
			case MIN30:
				return PERIOD_TRADE_HOURES * 2;
			case MIN60:
				return PERIOD_TRADE_HOURES * 1;
			default:
				return -1;
		}
	}

	/**
	 * 从自选list中获取股票代码list
	 * @param fundModels
	 * @return
	 */
	public static ArrayList<String> parseSelfFundStkNos(List<SelfFundModel> fundModels){
		if (fundModels == null || fundModels.size()==0) {
			return null;
		}
		ArrayList<String> queryResults = new ArrayList<String>(fundModels.size());
		if (fundModels!=null) {
			int size = fundModels.size();
			for (int i = 0; i < size; i++) {
				queryResults.add(fundModels.get(i).getStockNo());
			}
		}
		return queryResults;
	}

	public static String getSinaDayKUrl(String stkCode){
		String stkFull = parsetStkCode2ZB(stkCode)+stkCode;
		return getSinaDayKUrlWithFull(stkFull);
	}

	public static String getStkH5Line(String stockNo) {
//		http://stocks.sina.cn/sh/?code=sz002716&vt=4#H5Picture
		return "http://stocks.sina.cn/sh/?code="+parsetStkCode2ZB(stockNo)+stockNo+"&vt=4#H5Picture";
	}
	
	public static String getSinaDayKUrlWithFull(String stkFullCode){
		return "http://image.sinajs.cn/newchart/daily/n/"+stkFullCode+".gif";
	}
	
	/**用于新浪的查询
	 * 将代码前缀返回
	 * @param stkNo 证券代码  
	 * @return
	 */
	public static String parsetStkCode2ZB(String stkNo){
		//对指标成分进行处理
		if (stkNo.equals(SelfFundModel.CODE_SH)) {
			//上证
			return "sh";
		}else if (stkNo.equals(SelfFundModel.CODE_SZ)||stkNo.equals(SelfFundModel.CODE_CY)) {
			//深证以及中小板
			return "sz";
		}else {
			StringBuffer sb = new StringBuffer();
			String prefix = stkNo.substring(0, 3);
			if (prefix.equals("600")||prefix.equals("601")||prefix.equals("603")) {
				sb.append("sh");
			} else {
				sb.append("sz");
			}
			return sb.toString();
		}
	}
	
	public static boolean isStkValid(String stkNo){
		if (stkNo == null || stkNo.length()<6) {
			return false;
		}
		String prefix = stkNo.substring(0, 3);
		return prefix.equals("600")||prefix.equals("601")||prefix.equals("603")||prefix.equals("000")||prefix.equals("002")||prefix.equals("300")||prefix.equals("732");
	}
	
	public static String parseStkCode2Market(String stkCode){
		String preFix = stkCode.substring(0, 3);
		if (preFix.equals("600")||preFix.equals("601")||preFix.equals("603")||preFix.equals("732")) {
			return "1";
		} else {
			return "2";
		}
	}
	
	public static String parseStkCode2SecuId(String stkCode){
		String preFix = stkCode.substring(0, 3);
		if (preFix.equals("600")||preFix.equals("601")||preFix.equals("603")||preFix.equals("732")) {
			return "A303112208";
		} else {
			return "0186265187";
		}
	}


	public static List<SelfFundModel> getZBSelfFundModels(){
		List<SelfFundModel> models = new ArrayList<SelfFundModel>();
		SelfFundModel sh = new SelfFundModel();
		sh.setStockNo(SelfFundModel.CODE_SH);
		sh.setSourceCode(SelfFundModel.SOURCE_ZB);
		models.add(sh);
		
		SelfFundModel sz = new SelfFundModel();
		sz.setStockNo(SelfFundModel.CODE_SZ);
		sz.setSourceCode(SelfFundModel.SOURCE_ZB);
		models.add(sz);
		
		SelfFundModel cy = new SelfFundModel();
		cy.setStockNo(SelfFundModel.CODE_CY);
		cy.setSourceCode(SelfFundModel.SOURCE_ZB);
		models.add(cy);
		
		return models;
	}

	public static String priceOffsetType(float dis) {
		String disStr = "";
		if (dis < 0) {
			disStr = "下跌";
		} else {
			disStr = "上涨";
		}
		return disStr;
	}
	
	public static String parseTradeType(int tradeType){
		if (tradeType == OperateModel.TradeType_BUY) {
			return "买入";
		}else if (tradeType == OperateModel.TradeType_SELL) {
			return "卖出";
		}
		return "";
	}
	
	/**
	 * 获取问股返回的数量
	 * @param response
	 * @return
	 */
	public static String parseWgResponseCount(String response) {
		Pattern compile = Pattern.compile("\"total\":([0-9])*");
		Matcher matcher = compile.matcher(response);
		String totalCount = "";
		while(matcher.find()){
			totalCount = response.substring(matcher.start(), matcher.end());
			if (totalCount.length() > 8) {
				totalCount = totalCount.substring(8, totalCount.length());
			}
		}
		return totalCount;
	}





	public static String parseRow(String rows) {
		if (rows==null) {
			return null;
		}
		Pattern compile = Pattern.compile("[0-9]{6}");
		Matcher matcher = compile.matcher(rows);
		while(matcher.find()){
			String substring = rows.substring(matcher.start(), matcher.end());
			if (isStkValid(substring)) {
				return substring;
			}
		}
		return null;
	}
	
	
	
	/**
	 * 解析新浪的数据，返回当前价格
	 * @param result
	 * @param stkCode
	 * @return
	 */
	public static float parseSinaOnePrice(String result,String stkCode){
		if (result!=null) {
			Pattern compile = Pattern.compile("[0-9](.)*");
			Matcher matcher = compile.matcher(result);
			
			while(matcher.find()){
				String tmp = result.substring(matcher.start(), matcher.end());
				String[] split = tmp.split("=");
				String stkNo = split[0];
				if (stkNo!=null && stkNo.equals(stkCode)) {
					String info = split[1].substring(1, split[1].length()-2);
					String[] detail = info.split(",");
					if (detail!=null && detail.length>3) {
						return Float.valueOf(detail[3]);
					}
				}
				
			}
		}
		return 0;
	}


	public static HashMap<String, Object> parseWenguTableData(String response){
		Pattern compile = Pattern.compile("\\{\"data\":\\{(.)*]],");
		Matcher matcher = compile.matcher(response);
		String json = "";
		while(matcher.find()){
			json = response.substring(matcher.start(), matcher.end()-1) +"}}";
		}
		try {
			JSONObject obj = new JSONObject(json);
			JSONObject dataJson = obj.getJSONObject("data");
			HashMap<String, Object> resultHash = new HashMap<String, Object>();
			JSONArray titleArr = dataJson.getJSONArray(KEY_TITLE);
			if (titleArr != null && titleArr.length() > 0) {
				String[] header = new String[titleArr.length()];
				for (int i = 0; i < titleArr.length(); i++) {
					header[i] = titleArr.getString(i);
				}
				resultHash.put(KEY_TITLE, header);
			}

			JSONArray resultArr = dataJson.getJSONArray(KEY_RESULT);
			ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
			if (resultArr != null && resultArr.length() > 0) {
				for (int i = 0; i < resultArr.length(); i++) {
					JSONArray itemArr = resultArr.getJSONArray(i);
					if (titleArr!= null && itemArr!= null && itemArr.length()!=0) {
						if (itemArr.length() != titleArr.length()) {
							continue;
						}else {
							ArrayList<String> oneRow = new ArrayList<String>();
							for (int j = 0; j < itemArr.length(); j++) {
								oneRow.add(itemArr.getString(j));
							}
							results.add(oneRow);
						}
					}
				}
				resultHash.put(KEY_RESULT, results);
			}
			resultHash.put(KEY_COUNT, StockUtils.parseWgResponseCount(response));
			return resultHash;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	public static String getSimpleStkCode(String stkFullCode) {
		if (stkFullCode!=null && stkFullCode.length() == 9){
			return stkFullCode.substring(0, 6);
		}
		return "";
	}


}
